//
//  Engine.cpp
//  TrackingSim
//
//  Created by Garrett Manka on 2/17/12.
//  Copyright (c) 2012. All rights reserved.
//

#include <Engine.h>
#include <sim/Clock.h>
#include <ResourceManager.h>
#include <graphics/GraphicSystem.h>
#include <sim/KinematicSim.h>
#include <sim/PlayerLoader.h>
#include <graphics/ObjLoader.h>
#include <sim/Scenario.h>

bool Engine::s_instance_created = false;
Engine* Engine::s_the_instance = 0;

Engine::Engine():m_rate_hz(60.0),m_clock(new Utilities::Clock())
{

}

Engine::~Engine()
{
    delete m_clock;
    delete s_the_instance;
    s_the_instance = 0;
    s_instance_created = false;
}

void Engine::create()
{
    if(!s_instance_created)
    {
        s_the_instance = new Engine();
        s_instance_created = true;
    }
}

Engine* Engine::getEngine()
{
    if(!s_instance_created)
    {
        s_the_instance = new Engine();
        s_instance_created = true;
    }

    return s_the_instance;
}

void Engine::setRateHz(double rate_hz)
{
    m_rate_hz = rate_hz;
}

void Engine::load()
{
    //Create the Resource managers
    ResourceManager<Object>::createRM(ObjLoader::load);
    ResourceManager<Sim::Player>::createRM(PlayerLoader::load);
    
    //Load resources
    ResourceManager<Object>::getRM()->loadResource("f22small.obj");
    ResourceManager<Object>::getRM()->loadResource("fb4.obj");
    ResourceManager<Object>::getRM()->loadResource("terrain2.obj");
    ResourceManager<Sim::Player>::getRM()->loadResource("players.txt");
    
    //Create a scenario to use - change this into a resource to be loaded later
    Sim::Scenario s(60.0);
    s.addPlayers(ResourceManager<Sim::Player>::getRM()->getResourceList());
    s.setMainPlayer(ResourceManager<Sim::Player>::getRM()->getResourceByName("P1"));
    
    //Create Systems
    Sim::KinematicSim::create(&s);

    Sim::GraphicSystem::create(Sim::KinematicSim::getKS());
}

void Engine::start(int argc, char** argv)
{
    //Kick off the graphics system, which has the main processing loop for GLUT
    Sim::GraphicSystem::getGS()->start(argc, argv);
}